import React, { useState, useEffect, useCallback } from 'react';
import { NewsProps } from '../index';
import { Carousel, Empty } from 'antd';
import { InbizIcon } from '@inbiz/utils';
import SummaryItem from './components/summaryItem';
import { useEvents } from '@inbiz/utils';
import { getNewsList as getNewsListData } from '../../../service';
import { TextWidget } from '@inbiz/react';

const Arrow = ({ className: arrowClassName, type, ...restArrowProps }: any) => (
  <InbizIcon
    {...restArrowProps}
    className={arrowClassName}
    type={type === 'right' ? 'icon-ic-xianshi' : 'icon-ic-fanhui'}
  />
);

const NewsRollView: React.FC<NewsProps> = (props) => {
  const { pageSize, newsKey, standOut, autoRoll, delay = 3, showImage } = props;
  const fixNewKey = Array.isArray(newsKey) ? newsKey :newsKey? [newsKey]:[];
  const [newsList, setNewsList] = useState<Array<News.NewsItem>>([]);
  const [current, setCurrent] = useState(1);
  const [Total, setTotal] = useState(0);
  const [isInit, $init] = useState(false);
  const [configEvents] = useEvents(props.callBackEvents, props.emit)

  const getNewsList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onParams?.(params)) || params;
    const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
    return await configEvents.current?.onData?.(data) || data
  }, []);

  const getList = async (page: number, init?: boolean) => {
    const res: News.NewsList = await getNewsList({
      categoryId: fixNewKey?.map((item: any) => { return item.id }).toString(),
      pageIndex: page,
      pageSize: pageSize,
      showNew: standOut?.isStandout,
      numNew: standOut?.threshold || undefined,
    });
    const { ContentList = [], Total } = res;
    if (page === 1) {
      setNewsList(ContentList);
      init && $init(true)
    } else {
      setNewsList([...newsList, ...ContentList]);
    }
    setTotal(Total || 0);
  };

  useEffect(() => {
    if (!fixNewKey) return;
    getList(1, true);
  }, [newsKey]);

  const handleChange = useCallback(
    (curItem: number) => {
      if (newsList?.length - curItem <= 5 && newsList?.length < Total) {
        setCurrent(current + 1);
      }
    },
    [newsList, current],
  );

  useEffect(() => {
    getList(current);
  }, [current]);

  const prefixCls = 'inbiz-News-roll-view';

  return (
    <>
      {newsList?.length > 0 ?
       <Carousel
        className={`${prefixCls} eform-new-list`}
        arrows={true}
        nextArrow={<Arrow className={`${prefixCls}-btn`} type="right" />}
        prevArrow={<Arrow className={`${prefixCls}-btn`} type="left" />}
        dots={{ className: 'rasume-dots' }}
        dotPosition="bottom"
        afterChange={handleChange}
        autoplay={autoRoll}
        autoplaySpeed={delay * 1000}
      >

        {newsList?.map((item, index) => (
          <SummaryItem {...item} {...props} key={`${item.ID}_${index}`} showImage={showImage} />
        ))}

      </Carousel>:
      fixNewKey.length && !isInit ? null : 
       <div style={{ padding: '16px' }}>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={<TextWidget>News.noData</TextWidget>}
        />
      </div>
}
    </>

  );
};

export default NewsRollView;
